package com.lagou.framework.common;

import com.lagou.framework.util.HttpProtorcolUtil;
import com.lagou.framework.util.StaticResourceUtil;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author srh
 * @date 2020/03/31
 **/
@Data
@NoArgsConstructor
public class Response {

    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出静态资源
     *
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        // 获取静态资源文件的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        // 输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            // 读取静态资源文件，输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 输出404
            output(HttpProtorcolUtil.getHttpHeader404());
        }
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

}
